#!/bin/sh
# preinst script for salt-common.
#
# See: dh_installdeb(1).

set -e

# Summary of how this script can be called:
#        * <new-preinst> 'install'
#        * <new-preinst> 'install' <old-version>
#        * <new-preinst> 'upgrade' <old-version>
#        * <old-preinst> 'abort-upgrade' <new-version>
# for details, see https://www.debian.org/doc/debian-policy/ or
# the debian-policy package.

[ -n "$SALT_HOME" ] || SALT_HOME=/opt/saltstack/salt
[ -n "$SALT_USER" ] || SALT_USER=salt
[ -n "$SALT_NAME" ] || SALT_NAME="Salt"
[ -n "$SALT_GROUP" ] || SALT_GROUP=salt
[ -n "$SALT_SHELL" ] || SALT_SHELL=/usr/sbin/nologin

case "$1" in
  install|upgrade)
    # create user to avoid running server as root
    # 1. create group if not existing
    if ! getent group | grep -q "^$SALT_GROUP:" ; then
       echo -n "Adding group $SALT_GROUP.."
       groupadd --system $SALT_GROUP 2>/dev/null ||true
       echo "..done"
    fi
    # 2. create homedir if not existing
    test -d $SALT_HOME || mkdir -p $SALT_HOME
    # 3. create user if not existing
    if ! getent passwd | grep -q "^$SALT_USER:"; then
      echo -n "Adding system user $SALT_USER.."
      useradd --system \
              --no-create-home \
              -s $SALT_SHELL \
              -g $SALT_GROUP \
              $SALT_USER 2>/dev/null || true
      echo "..done"
    fi
    # 4. adjust passwd entry
    usermod -c "$SALT_NAME" \
            -d $SALT_HOME   \
            -s $SALT_SHELL  \
            -g $SALT_GROUP  \
             $SALT_USER

    # Remove incorrectly installed logrotate config - issue 65231
    test -d /etc/logrotate.d/salt && rm -r /etc/logrotate.d/salt || /bin/true

  ;;

  abort-upgrade)
  ;;

  *)
    echo "preinst called with unknown argument '$1'" >&2
    exit 1
  ;;
esac

# dh_installdeb will replace this with shell code automatically
# generated by other debhelper scripts.

#DEBHELPER#

exit 0
